package com.jinzecloud.fiction.service.impl;

import com.jinzecloud.fiction.bean.TbBookContent;
import com.jinzecloud.fiction.bean.TbCatalogue;
import com.jinzecloud.fiction.constant.Constant;
import com.jinzecloud.fiction.mapper.TbBookContentMapper;
import com.jinzecloud.fiction.mapper.TbCatalogueMapper;
import com.jinzecloud.fiction.service.TbBookContentService;
import com.jinzecloud.fiction.service.TbCatalogueService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinzecloud.fiction.utils.PageUtils;
import com.jinzecloud.fiction.utils.Query;

import com.jinzecloud.fiction.mapper.TbBookNameMapper;
import com.jinzecloud.fiction.bean.TbBookName;
import com.jinzecloud.fiction.service.TbBookNameService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


@Service("tbBookNameService")
public class TbBookNameServiceImpl extends ServiceImpl<TbBookNameMapper, TbBookName> implements TbBookNameService {

    @Autowired
    private TbBookNameMapper tbBookNameMapper;
    @Autowired
    private TbCatalogueService tbCatalogueService;
    @Autowired
    private TbBookContentService tbBookContentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<TbBookName> tbBookNameQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            tbBookNameQueryWrapper.eq("bn_id", key);
        }
        if (!StringUtils.isEmpty(key)) {
            tbBookNameQueryWrapper.or().like("bn_name", key);
        }
        IPage<TbBookName> page = this.page(new Query<TbBookName>().getPage(params), tbBookNameQueryWrapper);

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public String saveTbBookName(MultipartFile file) {//TbBookName tbBookName,
        // TODO 待优化方法 统一上传文件格式后再处理
        Charset charset = Charset.forName("UTF-8");
        Pattern p = Pattern.compile(Constant.DEFAULT_PATTERN);
        String bnDigest = null;
        TbCatalogue tbCatalogue = null;
        int bookId = 0;
        int catalogueId = 0;
        AtomicInteger i = new AtomicInteger(1);
        int j = 1;
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            try {
                byte[] bytes = file.getBytes();
                String fileContent = new String(bytes, charset);
                int length = (fileContent.trim().length());
                List<String> list = new ArrayList<>();
                for (String s : fileContent.split(p.pattern())) {
                    list.add(s);
                }
                Matcher m = p.matcher(fileContent);
                bnDigest = list.get(i.get()).substring(0, 150) + "....";
                TbBookName tbBookName = new TbBookName();
                tbBookName.setBnName(fileName.substring(0, fileName.lastIndexOf(".")));
                tbBookName.setBnNumberWords(length);
                tbBookName.setBnStatus(1);
                Date date = new Date();
                tbBookName.setBnCreationTime(date);
                tbBookName.setBnUpdateTime(date);
                tbBookName.setBnDigest(bnDigest);
                bookId = tbBookNameMapper.insert(tbBookName);
                List<TbCatalogue> tbCatalogues = new ArrayList<>();

                while (m.find()) {
                    String title = m.group(0).replace("\r\n", " ").replace(" ===", "").trim() + "\n";
                    tbCatalogue = new TbCatalogue();
                    tbCatalogue.setCatBookNameId(bookId);
                    tbCatalogue.setCatCatalogueName(title);
                    tbCatalogues.add(tbCatalogue);
                }
                tbCatalogueService.saveBatch(tbCatalogues);
                tbBookContentService.saveBatch(tbCatalogues.stream().map(item -> {
                    TbBookContent bookContent = new TbBookContent();
                    bookContent.setCoCatalogueId(item.getCatId());
                    bookContent.setCoContent(list.get(i.getAndIncrement()));
                    bookContent.setCoStatus("1");
                    bookContent.setCoCreationTime(new Date());
                    bookContent.setCoUpdateTime(new Date());
                    return bookContent;
                }).toList());
                return "上传成功";
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "上传失败";
    }
}